//
//  ComSaveViewController.m
//  CarFace
//
//  Created by dlios on 15-4-2.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "ComSaveViewController.h"
#import "CommentViewController.h"
#import "DataHander.h"
#import "UIButton+InitButton.h"
@interface ComSaveViewController ()<UITableViewDelegate, UITableViewDataSource>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *array;
@property(nonatomic, retain)NSString *idStr;
@property(nonatomic, retain)UIButton *editButton;
@property(nonatomic, assign)BOOL flag;
@end

@implementation ComSaveViewController


- (void)dealloc
{
    [_tableView release];
    [_array release];
    [_idStr release];
    [super dealloc];


}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *returnButton = [UIButton buttonWithTitle:@"返回" frame:CGRectMake(0, 20, self.view.frame.size.width / 4,20) target:self action:@selector(clickReturnButton:)];
    [returnButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [returnButton setImage:[UIImage imageNamed:@"iconfont-fanhui.png"] forState:UIControlStateNormal];
    [self.view addSubview:returnButton];
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2  - 30, 50, 60, 40)];
    title.text = @"收藏夹";
    title.textAlignment = NSTextAlignmentCenter;
    title.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:title];
    [title release];
    
    self.editButton = [UIButton buttonWithTitle:@"编辑" frame:CGRectMake(self.view.frame.size.width * 4 / 5, self.view.frame.size.height / 16, self.view.frame.size.width / 4,20) target:self action:@selector(clickEditButton:)];
    //    [editButton setImage:[UIImage imageNamed:@"iconfont-shanchu.png"] forState:UIControlStateNormal];
    [self.editButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:self.editButton];
    
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(5, 100, self.view.frame.size.width - 10, self.view.frame.size.height - 55 - 100) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView addHeaderWithTarget:self action:@selector(addHeader:)];
    [self.tableView addFooterWithTarget:self action:@selector(addFooter:)];
    [self.tableView setHeaderRefreshingText:@"下拉刷新"];
    [self.tableView setFooterRefreshingText:@"网络加载中..."];
    
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    
    //  引用数据库,打开数据库
    [[DataHander shareInstance] openDB];
    self.array = [NSMutableArray array];
    // 取到所有的数据放到数组里
    self.array = [[DataHander shareInstance] selectAll];
    [_tableView reloadData];
    
    
}


#pragma mark - tableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"reque";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str]autorelease];
    }
    cell.textLabel.text = [[self.array objectAtIndex:indexPath.row] bbsname];
    self.idStr = [[self.array objectAtIndex:indexPath.row] bbsid];
    return cell;
    
}


//保存了 bbsid 和 bbname

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentViewController *comVC = [[CommentViewController alloc]init];
    comVC.foru = [self.array objectAtIndex:indexPath.row];
    [self presentViewController:comVC animated:YES completion:^{
        
    }];
    [comVC release];
    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
        return UITableViewCellEditingStyleDelete;
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"dd");
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //   当点击删除按钮时,对试图做操作时,要先对数据源做处理
        [self.array removeObjectAtIndex:indexPath.row];
        [[DataHander shareInstance] deleteData:self.idStr];

        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
    }
}



- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    //移动之后执行的方法
    //    1,从数据源取值
    NSString *name = [[[self.array objectAtIndex:sourceIndexPath.row] bbsname ]retain];
    //    2.从原来的位置移除
    [self.array removeObjectAtIndex:sourceIndexPath.row];
    //    3.放到新的位置
    [self.array insertObject:name atIndex:destinationIndexPath.row];
    [name release];
}

- (void)clickEditButton:(UIButton *)button
{
   
    if (self.flag == NO) {
        [_tableView setEditing:YES animated:YES];
        [_tableView allowsSelectionDuringEditing];
        [self.editButton setTitle:@"取消" forState:UIControlStateNormal];
    }else{
        [_tableView setEditing:NO animated:YES];
        [self.editButton setTitle:@"编辑" forState:UIControlStateNormal];
        
    }
    self.flag =! self.flag;
}

- (void)clickReturnButton:(UIButton *)button
{
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}



#pragma mark - 刷新的方法
- (void)addHeader:(UITableView *)header;
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加下拉刷新头部控件
    [self.tableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        NSLog(@"KKk______kk");
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc.tableView reloadData];
            // 结束刷新
            [vc.tableView headerEndRefreshing];
            NSLog(@"KKkkk");
        });
    } dateKey:@"collection"];
    // dateKey用于存储刷新时间，也可以不传值，可以保证不同界面拥有不同的刷新时间
    
}

- (void)addFooter:(UITableView *)footer
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加上拉刷新尾部控件
    [self.tableView addFooterWithCallback:^{
        [self.tableView addHeaderWithTarget:self action:@selector(searchBarSearchButtonClicked:)];
        
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc.tableView reloadData];
            // 结束刷新
            [vc.tableView footerEndRefreshing];
            
        });
    }];
}

 

    


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
